package com.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.*;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.nio.charset.Charset;

class  RecvMessageFromBaidu extends SimpleChannelInboundHandler<FullHttpResponse> {

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, FullHttpResponse response) throws Exception {
        //得到响应内容
        ByteBuf result = response.content();
        String str = result.toString(Charset.defaultCharset());
        System.out.println("收到的消息:"+str);
    }
}

class InitHandler extends ChannelInitializer {

    @Override
    protected void initChannel(Channel channel) throws Exception {
        System.out.println("客户端初始化了");

        //http客户端编码器
        channel.pipeline().addLast(new HttpClientCodec());
        //聚合编码器(请求头，和请求体在一起,响应头，响应体在一起，打包)
        channel.pipeline().addLast(new HttpObjectAggregator(Integer.MAX_VALUE));
        channel.pipeline().addLast(new RecvServerMessage());
    }
}

public class BaiduClient {
    public static void main(String[] args) throws InterruptedException {
        //1.引导器
        Bootstrap b = new Bootstrap();
        //2.事件组
        EventLoopGroup workGroup = new NioEventLoopGroup();
        b.group(workGroup);
        //3.设置通道类型
        b.channel(NioSocketChannel.class);
        //4.初始化
        b.handler(new InitHandler());
        //5.连接服务器，并发送消息到服务器
        ChannelFuture cf = b.connect("www.baidu.com", 80).sync();

        String url = "http://www.baidu.com";
        FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, url);
        cf.channel().writeAndFlush(request);
        //6.关闭
        cf.channel().closeFuture().sync();
        workGroup.shutdownGracefully();


    }
}
